import random
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework import serializers
from . import constants
from celery_tasks.sms.tasks import send_sms_code


# /sms_code/(?P<mobile>1[3-9]\d{9})/
class SMSCodeView(GenericAPIView):
    """
    短信验证码，传入mobile
    """

    def get(self, request, mobile):
        """创建短信验证码"""

        # 连接redis
        redis_cli = get_redis_connection('sms_code')
        # 检查60s之内是否发过短信
        if redis_cli.get('sms_flag_' + mobile):
            raise serializers.ValidationError("发送验证码过于频繁")

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        print("短信验证码：", sms_code)

        pl = redis_cli.pipeline()
        pl.setex("sms_code_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        # 发送短信验证码
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, sms_code_expires], 1)
        # celery里面已经封装了发短信模块，我们用里面的方法，直接
        # 传手机，验证码和过期时长就够了，里面模板id已经写好了
        # send_sms_code.delay(mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60)

        return Response({"message": "OK"})


